package logiexport.carrito;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import logiexport.paneles.PanelPresu;
import logiexport.pojos.Presupuesto;
import logiexport.pojos.Producto;
import logiexport.pojos.User;
import logiexport.session.SignInSession;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.ListChoice;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.PropertyModel;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import logiexport.bd.*;

public class PanelCarrito extends Panel {

	private List<Producto> lista = new ArrayList<Producto>();
	private int total_unidades = 0;
	private float total_euros = 0;	
	private Presupuesto simulador = new Presupuesto ();
	private App app = new App();
	int id_p;
	private Integer idpresu;
	private List<Integer> listaids;
	private Presupuesto p1 = new Presupuesto();
	
	//private List<Integer> listaids = Arrays.asList(new Integer[] {
			//1,2,3 });
	
	
	
	SignInSession s = SignInSession.get();
	User u = s.getUser();
	
	public PanelCarrito(String id, final PanelPresu panelpresu) {
		super(id);
		// TODO Auto-generated constructor stub

		onConfigure();	
		
		listaids = app.lista_idspresu(u);
		
		Label total_eur = new Label("total", new PropertyModel(simulador, "total"));
		
	
		
		@SuppressWarnings("unchecked")
		ListView listview = new ListView("productslist", lista) {

			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@SuppressWarnings("rawtypes")
			@Override
			protected void populateItem(ListItem item) {

				// Tomo el usuario correspondiente a este item de la lista
				final Producto p = (Producto) item.getModelObject();
				
				
				item.add(new Label("tipo", p.getNombre()));
				item.add(new Label("tallo", p.getTallo()));
				item.add(new Label("color", p.getColor()));
				item.add(new Label("precio", p.getPrecio()));				
				item.add(new Label("cantidad", p.getUnidades()));
				item.add(new Label("total",p.getPrecio()));
				
			

			}
		};

		add(listview);	
		
		add(total_eur);
		
		
		Form<Void> presuform = new Form<Void>("presuform", new CompoundPropertyModel(this));
			
		add(presuform);
		
		final Presupuesto p = new Presupuesto();
		
		
		 presuform.add(new ListChoice<Integer>("idpresu", new PropertyModel<Integer>(p, "id_p") , new PropertyModel<List<Integer>>(this, "listaids")));
			
			//TextField<String> tidpresu = new TextField <String>("idpresu");
			
			 AjaxButton presubutton = new AjaxButton("presuboton") {
				 
				 protected void onSubmit(AjaxRequestTarget target,
							Form<?> form) {
					 
					 
					 System.out.println("Presu id: "+p.getId_p());		 
					 
					 
					p1 = app.presu(p);
					
					System.out.println("Presu id: "+p1.getTotal());
					
			
				
					 
				
				 }
				 
				 
			 };
			// presuform.add(tidpresu);
			 presuform.add(presubutton);	 
			 
			 
				@SuppressWarnings("unchecked")
				ListView presulist = new ListView("presulist", p1.getProductos()) {

					/**
					 * 
					 */
					private static final long serialVersionUID = 1L;

					@SuppressWarnings("rawtypes")
					@Override
					protected void populateItem(ListItem item) {

						// Tomo el usuario correspondiente a este item de la lista
						final Producto p = (Producto) item.getModelObject();
						
						
						item.add(new Label("ptipo", p.getNombre()));
						item.add(new Label("ptallo", p.getTallo()));
						item.add(new Label("pcolor", p.getColor()));
						item.add(new Label("pprecio", p.getPrecio()));				
						item.add(new Label("pcantidad", p.getUnidades()));
						item.add(new Label("ptotal",p.getPrecio()));							
					

					}
				};
			
				add(presulist);
		
		
		AjaxLink<String> pdf = new AjaxLink<String>("pdf") {

			@Override
			public void onClick(AjaxRequestTarget target) {
				// TODO Auto-generated method stub			
			
				Presupuesto presu = new Presupuesto ();
				
				id_p=app.last_presupuesto();
				id_p++;		
				
		
								
				System.out.println("Numero de presupuesto: "+id_p);

				String fecha = "2014-07-24";
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

				try {

					java.util.Date date = sdf.parse(fecha);

					java.sql.Date sqlDate = new Date(date.getTime());
					
					System.out.println("Date: " + sqlDate);				
					
					presu.setFecha_e(sqlDate);
					presu.setFecha_p(sqlDate);
					presu.setTransporte("RA");
					presu.setCantidad(total_unidades);
					presu.setObs("");
					presu.setConfirmado(0);
					presu.setTotal(total_euros);				

		
					presu.setProductos(lista);	
				
					
					app.add_presu(u, presu);
					System.out.println("Add presu 0");
					
					panelpresu.configure();
					target.add(panelpresu);
		
					Gson gson = new GsonBuilder().setDateFormat("dd-MM-yyyy")
							.create();
	
					String usergson = gson.toJson(u);				
					String presugson = gson.toJson(presu);		


					System.out.println("UserGson: " + usergson);
					System.out.println("PresuGson: " + presugson);
					
					


					DefaultHttpClient httpClient = new DefaultHttpClient();

					HttpPost request = new HttpPost(
							"http://localhost/pdf/pdf.php");

					List<NameValuePair> postParams = new ArrayList<NameValuePair>();

					postParams.add(new BasicNameValuePair("usuario", usergson));
					postParams.add(new BasicNameValuePair("presupuesto",
							presugson));
					postParams.add(new BasicNameValuePair("id_p",Integer.toString(id_p)));

					UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
							postParams);

					entity.setContentEncoding(HTTP.UTF_8);
					entity.setContentType("application/json");
					request.setEntity(entity);

					request.addHeader("content-type",
							"application/x-www-form-urlencoded");

					HttpResponse response = httpClient.execute(request);
		

					System.out.println("Estado: "
							+ response.getStatusLine().getStatusCode());

					BufferedReader rd = new BufferedReader(
							new InputStreamReader(response.getEntity()
									.getContent()));
					String line = "";
					while ((line = rd.readLine()) != null) {
						System.out.println(line);
					}
					
				

				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			
				target.add(PanelCarrito.this);
			}
			
			
			
			
			
		};

		add(pdf);
		
	}

	@Override
	protected void onConfigure() {
		// TODO Auto-generated method stub
		super.onConfigure();
		
		//listaids.clear();
		listaids = app.lista_idspresu(u);
		
		total_unidades = 0;
		total_euros = 0;

		// lista.clear();
		lista = ProductSingleton.getInstance().getProductos();	


		for (int i = 0; i < lista.size(); i++) {

			total_unidades = total_unidades + lista.get(i).getUnidades();
			total_euros = total_euros + lista.get(i).getTotal();

		}
		
		
		simulador.setTotal(total_euros);


	}
	


}
